from celery.utils.serialization import jsonify
from django.db import DatabaseError
from django.shortcuts import render, redirect
from django.views import View
from django import http
import re
from useres.models import User
from ihome.utils.response_code import RET
from django_redis import get_redis_connection
from django.contrib.auth import authenticate, login, logout
from django.conf import settings
import json

# 1, 注册页面视图


class RegisterView(View):
    def post(self, request):
        # 一、接收参数---根据接口文档
        dict_data = json.loads(request.body.decode())
        mobile = dict_data.get("mobile")
        phonecode = dict_data.get("phonecode")
        password = dict_data.get("password")

        # 二、校验参数

        # 判断参数是否齐全
        if not all([mobile, phonecode, password]):
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数不全"})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "请输入8-20位的密码"})

        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "请输入正确的手机号码"})

        # 校验用户输入的手机验证码和redis保存的手机验证码是否一致
        redis_conn = get_redis_connection("code")
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if not real_sms_code:
            return http.JsonResponse({"errno": RET.NODATA, "errmsg": "验证码已经过期"})

        if real_sms_code.decode() != phonecode:
            return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "验证码输入错误"})
        # 三、业务逻辑
        save_data = {
            "username": mobile,
            "mobile": mobile,
            "password": password
        }
        try:
            user = User.objects.create_user(**save_data)
        except DatabaseError as e:

            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "注册失败"})
        # 状态保持
        login(request, user)

        # 四、返回响应
        return http.JsonResponse({"errno": RET.OK, "errmsg": "注册成功"})

    #     if not re.match(r'^1[3-9]\d{9}$', mobile):
    #         return http.HttpResponseForbidden("手机号格式有误")
    #
    #     if password != password2:
    #         return http.HttpResponseForbidden("两次密码不一致")
    #
    #     redis_conn = get_redis_connection("code")
    #     redis_sms_code = redis_conn.get("sms_code_%s" % mobile)
    #     if phonecode != redis_sms_code.decode():
    #         return http.HttpResponseForbidden("短信验证码填写错误")
    #
    #     login(request, mobile)  # 就是将用户的信息存储在session
    #     request.session.set_expiry(3600 * 24 * 2)  # 两天
    #
    #     return redirect('index.html')
    #
    # def get(self, request):
    #     return render(request, 'index.html')

class LoginView(View):

    def post(self, request):
        # 1,获取参数
        dict_data = json.loads(request.body.decode())
        mobile = dict_data.get("mobile")
        password = dict_data.get("password")
        remembered=dict_data.get("remembered")

        # 2,校验参数
        # 2,1 为空校验
        if not all([mobile, password]):
            return http.JsonResponse("参数不全")

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse("请输入正确的手机号码")

        # 2,3 密码格式校验
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse("密码格式不对")

        # 2,4 账号密码正确性校验, 如果认证成功返回用户对象, 不成功返回None
        mobile = authenticate(request, username=mobile, password=password)

        if not mobile:
            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "登陆失败"})

        login(request, mobile)  # 就是将用户的信息存储在session
        if remembered == "on":
            request.session.set_expiry(3600 * 24 * 2)  # 两天
        else:
            request.session.set_expiry(0)  # 一次浏览器会话结束

            # 四、返回响应
        return http.JsonResponse({"errno": RET.OK, "errmsg": "登陆成功"})

    def get(self,request):

        # 1、判断用户是否登录，需要获取user
        user = request.user
        # 2、对user进行认证
        if not user.is_authenticated:
            return http.JsonResponse({"errno": RET.SESSIONERR, "errmsg": "用户未登录"})

        data = {
            "user_id": user.id,
            "name": user.username
        }
        return http.JsonResponse({"errno": RET.OK, "errmsg": "已登录", "data": data})


    def delete(self,request):

        logout(request)

        # request.delete_cookie("name")
        return http.JsonResponse({"errno": RET.OK, "errmsg": "已登出"})


    # """退出"""
    #     # 清除session数据
    #     session.clear()
    #     return jsonify(errno=RET.OK, errmsg='ok')



        #
        #
        # mobile = request.GET.get("mobile")
        # password = request.GET.get("password")
        #
        #
        # save_data = {
        #     "name": mobile,
        # }
        # try:
        #     user = User.objects.create_user(**save_data)
        # except DatabaseError as e:
        #
        #     return http.JsonResponse({"errno": RET.DBERR, "errmsg": "未登录"})
        #
        # login(request, mobile)  # 就是将用户的信息存储在session
        # if remembered == "on":
        #     request.session.set_expiry(3600 * 24 * 2)  # 两天
        # else:
        #     request.session.set_expiry(0)  # 一次浏览器会话结束
        #
        # # 四、返回响应
        # return http.JsonResponse({"errno": RET.OK, "errmsg": "已登陆"})













        # def login():
    #     """登陆
    #     传递参数： 手机号、密码，
    #     格式为：json
    #     """
    #     # 获取参数
    #     req_dict = request.get_json()
    #     mobile = req_dict.get('mobile')
    #     password = req_dict.get('password')
    #
    #     # 验证参数的完整性
    #     if not all([mobile, password]):
    #         return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    #
    #     # 验证手机号的格式
    #     if not re.match(r'1[34578]\d{9}', mobile):
    #         return jsonify(errno=RET.PARAMERR, errmsg='手机号格式错误')
    #
    #     # 判断登陆错误的次数，超过限制，则返回
    #     user_ip = request.remote_addr  # 获取用户的ip地址
    #     try:
    #         access_nums = redis_store.get('access_num_%s' % user_ip)
    #     except Exception as e:
    #         current_app.logger.error(e)
    #     else:
    #         if access_nums is not None and int(access_nums) > constants.LOGIN_ERROR_MAX_TIMES:
    #             return jsonify(errno=RET.REQERR, errmsg='登陆失败次数过多，请稍后重试')
    #
    #     # 从数据库中查询用户手机号对应的对象数据
    #     try:
    #         user = User.query.filter_by(mobile=mobile).first()
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return jsonify(errno=RET.DBERR, errmsg='获取用户信息失败')
    #
    #     # 将用户填写的密码与数据库中的密码进行对比验证
    #     if user is None or not user.check_password(password):
    #         try:
    #             # 如果验证失败，记录错误次数，返回信息
    #             redis_store.incr('access_num_%s' % user_ip)
    #             redis_store.expire('access_num_%s' % user_ip, constants.LOGIN_ERROR_FORBID_TIME)
    #         except Exception as e:
    #             current_app.logger.error(e)
    #         return jsonify(erno=RET.DATAERR, errmsg='手机号或密码错误')
    #
    #     # 如果验证成功，保存登陆状态至session中
    #     session['name'] = user.name
    #     session['mobile'] = user.mobile
    #     session['user_id'] = user.id
    #
    #     return jsonify(errno=RET.OK, errmsg='登陆成功')
    #
    # def logout():
    #     """退出"""
    #     # 清除session数据
    #     session.clear()
    #     return jsonify(errno=RET.OK, errmsg='ok')






































